# -*- coding: UTF-8 -*-
from PySide6.QtWidgets import QDialog, QVBoxLayout, QTableWidget, QTableWidgetItem, QPushButton
import jwt


def show_device_details(parent, row, devices):
    if row < 0 or row >= len(devices):  # 检查 row 是否在有效范围内
        parent.QMessageBox.warning(parent, "警告", "选择的设备索引无效")
        return

    device = devices[row]
    dialog = QDialog(parent)
    dialog.setWindowTitle("设备详情")
    layout = QVBoxLayout(dialog)
    
    # 获取当前用户角色
    current_user = None
    main_window = parent
    while main_window and not hasattr(main_window, 'settings'):
        main_window = main_window.parent()
    
    if main_window and hasattr(main_window, 'settings'):
        token = main_window.settings.value('user_token')
        if token:
            try:
                current_user = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
            except jwt.ExpiredSignatureError:
                pass

    # 创建表格显示设备信息
    details_table = QTableWidget()
    details_table.setColumnCount(2)
    details_table.setHorizontalHeaderLabels(["属性", "值"])
    
    # 设置要显示的设备属性
    device_attrs = [
        ("厂商", "vendor"),
        ("设备类型", "device_type"),
        ("型号", "model"),
        ("主机名", "host"),
        ("IP地址", "ip"),
        ("远程类型", "remote_type"),
        ("协议", "protocol"),
        ("端口", "port"),
        ("用户名", "username"),
        ("密码", "password"),
        ("Enable密码", "enable_password"),
        ("在线状态", "online"),
        ("版本", "version"),
        ("CPU使用率", "cpu"),
        ("内存使用率", "memory"),
        ("启动时长", "uptime"),
        ("风扇状态", "fan"),
        ("电源状态", "power"),
        ("温度", "temperature"),
        ("更新时间", "update_time")
    ]
    
    details_table.setRowCount(len(device_attrs))
    
    for row, (label, key) in enumerate(device_attrs):
        # 设置属性名
        attr_item = QTableWidgetItem(label)
        details_table.setItem(row, 0, attr_item)
        
        # 设置属性值
        value = device.get(key, "")
        
        # 处理密码显示
        if key in ["password", "enable_password"]:
            if current_user and current_user.get('role') == '管理员':
                value_item = QTableWidgetItem(str(value))
            else:
                value_item = QTableWidgetItem("********")
        else:
            value_item = QTableWidgetItem(str(value))
        
        details_table.setItem(row, 1, value_item)
    
    # 调整表格大小
    details_table.resizeColumnsToContents()
    details_table.setMinimumWidth(200)
    details_table.setMinimumHeight(400)
    
    layout.addWidget(details_table)
    
    # 添加关闭按钮
    close_button = QPushButton("关闭")
    close_button.clicked.connect(dialog.close)
    layout.addWidget(close_button)
    
    dialog.exec()
